package org.lmind.example.util.text;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.lmind.example.util.text.PlaceholderResolver.Resolver;

/**
 * <p>正则表达式的文本替换模板</p>
 * <pre>
 * PatternTextTemplate template = new PatternTextTemplate(
 *     Pattern.compile("(\\w)\\+(\\w)=(\\w)"), 
 *     "${3}-${1}=${2}");
 * String output = template.transform("a+b=x");
 * assertEquals("x-a=b", output);
 * </pre>
 * @author mian.liu
 *
 */
public class PatternTextTemplate implements TextTemplate {
	
	private static PlaceholderResolver placeholderResolver = new PlaceholderResolver();
	
	private Pattern pattern;
	
	private String template;

	public PatternTextTemplate(Pattern pattern, String template) {
		this.pattern = pattern;
		this.template = template;
	}

	public Pattern getPattern() {
		return pattern;
	}

	public String getTemplate() {
		return template;
	}

	public String transform(String text) {
		return PatternTextTemplate.transform(pattern, template, text);
	}
	
	public static String transform(Pattern pattern, String template, String text) {
		
		Matcher matcher = pattern.matcher(text);
		if (!matcher.find())
			return null;
		
		Resolver resolver = placeholderResolver.resolver(template);
		while (resolver.next()) {
			int num = 0;
			try {
				num = Integer.parseInt(resolver.getKey());
			} catch (NumberFormatException e) {
				break;
			}
			if (num <= matcher.groupCount()) {
				resolver.replace(matcher.group(num));
			}
		}
		return resolver.build();
	}

}
